<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/js.cookie.js"></script>
    <style>
        table,
        tr,
        td,
        th {
            border: 1px solid #0094ff;
            text-align: center;
        }

        table {
            width: 600px;
            border-collapse: collapse;
            border-spacing: 0px;
        }
    </style>
</head>

<body>
    <table>
        <thead>
            <tr>
                <th>编号</th>
                <th>名称</th>
                <th>价格</th>
                <th>数量</th>
                <th>金额</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="tab">

        </tbody>
    </table>

    <script>
        //1.获取表格
        var oTab = document.querySelector("#tab");
        //2.获取磁盘的数据(物理数据的cookie)
        var oCarts = JSON.parse(Cookies.get("carts") || '[]');

        var strHtml = '';
        oCarts.forEach(function (item, index) {
            strHtml += `
                <tr>
                    <td>${item.id}</td>
                    <td>${item.name}</td>
                    <td>${item.price}</td>
                    <td>
                        <button>-</button>
                       <input style='width:20px' value=${item.number}>
                        <button>+</button>
                    </td>
                    <td>${item.price * item.number}</td>
                    <td><a class='del' data-id=${item.id} href='javascript:void(0)'>删除</a></td>
                </tr>
            `
        });
        oTab.innerHTML = strHtml

        //事件委托
        oTab.addEventListener("click", function (evt) {
            var e = evt || window.event;
            var ele = e.target || e.srcElement;
            if (!(ele.nodeName == 'A' && ele.className == 'del')) {
                return;
            }
            //根据id删除本地数据
            var id = ele.getAttribute("data-id");
            //本地数据
            var oCarts = JSON.parse(Cookies.get("carts") || '[]');
            oCarts.forEach(function (item, index) {
                if (item.id == id) {
                    //删除内存条中的数据
                    oCarts.splice(index, 1);
                }
            })

            //把已经发生变化的内存条数据,覆盖物理磁盘上的数据
            Cookies.set("carts", oCarts)

            //删除视觉效果
            ele.parentNode.parentNode.remove();

        })

    </script>
</body>

</html>